package com.zhuang.taiqiu.utils;

import com.alibaba.fastjson.JSON;
import com.zhuang.taiqiu.proto.GameMessageOuterClass;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

public class NettyUtil {

    /****
     * 系统发消息给一个玩家
     * @param ctx
     * @param data
     * @param command
     */
    public static void sendMsg(Channel ctx, Object data, String command){
        BinaryWebSocketFrame sendingEntity = CreateSendingEntity(data, command);
        ctx.writeAndFlush(sendingEntity);
    }

    /**
     * 群发给一个房间内的所有玩家
     * @param group
     * @param data
     * @param command
     */
    public static void sendGroupMsg(ChannelGroup group, Object data, String command){
        BinaryWebSocketFrame sendingEntity = CreateSendingEntity(data, command);
        group.writeAndFlush(sendingEntity);
    }


    private static BinaryWebSocketFrame CreateSendingEntity(Object data, String command) {
        String jsonString = JSON.toJSONString(data);

        GameMessageOuterClass.GameMessage alice = GameMessageOuterClass.GameMessage.newBuilder()
                .setCommand(command)
                .setData(jsonString)
                .setTimestamp(System.currentTimeMillis())/**这个时间分布式不知道怎么搞*/
                .build();

        // 将 Alice 的消息编码为二进制数据
        byte[] aliceBytes = alice.toByteArray();
        // 创建一个 ByteBuf 来存储二进制数据
        ByteBuf encodedAliceMessage = ByteBufAllocator.DEFAULT.buffer(aliceBytes.length);
        encodedAliceMessage.writeBytes(aliceBytes);
        // 创建一个 BinaryWebSocketFrame 包含编码后的二进制数据
        // 在 ChannelHandlerContext 上发送 WebSocket 消息
        return new BinaryWebSocketFrame(encodedAliceMessage);
    }
}
